﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace socketForm
{
    public static class SocketUtil
    {
        public static string getIP()
        {
            //获取本机IP

            //方式一
            //var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            //foreach (var networkInterface in networkInterfaces)
            //{
            //    if (networkInterface.OperationalStatus == OperationalStatus.Up)
            //    {
            //        var ipProperties = networkInterface.GetIPProperties();
            //        var ipAddresses = ipProperties.UnicastAddresses;
            //        foreach (var ipAddress in ipAddresses)
            //        {
            //            if (ipAddress.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
            //            {
            //                var ipv4Address = ipAddress.Address.ToString();
            //                Console.WriteLine("IPv4 Address: " + ipv4Address);
            //            }
            //        }
            //    }
            //}

            //方式二
            var hostName = Dns.GetHostName();
            var ipHost = Dns.GetHostEntry(hostName);
            var ipAddress = ipHost.AddressList.FirstOrDefault(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
            if (ipAddress != null)
            {
                var ipv4Address = ipAddress.ToString();
                Console.WriteLine("IPv4 Address: " + ipv4Address);
                return ipv4Address;
            }
            else
            {
                return null;
            }

            //方式三
            //var query = new SelectQuery("SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'");
            //var searcher = new ManagementObjectSearcher(query);
            //var managementObjects = searcher.Get();

            //foreach (var managementObject in managementObjects)
            //{
            //    var ipAddress = managementObject["IPAddress"] as string[];
            //    if (ipAddress != null && ipAddress.Length > 0)
            //    {
            //        foreach (var ip in ipAddress)
            //        {
            //            Console.WriteLine("IP Address: " + ip);
            //        }
            //    }
            //}
        }

    }
}
